<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/12/28
 * Time: 18:05
 */
namespace app\common\model;
require_once EXTEND_PATH."Wxpay/lib/WxPay.Api.php";
include_once  EXTEND_PATH . "alipay/AopSdk.php";
use think\Cache;
use think\Exception;
use think\Model;
use app\common\model\WeixinPay;
use app\common\model\ServerException;
use app\common\model\DeveloperException;
class Pay extends Common
{
    /**
     * 微信支付APP
     *
     * @param string $price 支付金额
     * @param string $orderSn 订单号
     * @param array $body 描述
     * @return array|false
     * @throws ServerException
     */
    static public function weixinPay($orderSn,$price,$body,$notify='')
    {
        $weixin=new WeixinPay();
        $price=round($price,2);
        $reponse=$weixin->getPrePayOrder($body, $orderSn, $price,$notify);
        $payInfo=[];
        if($reponse['return_code']=='SUCCESS' && $reponse['result_code']=='SUCCESS')
        {
            $payInfo['appid']=config('weixinpay.appid');
            $payInfo['partnerid']=$reponse['mch_id'];
            $payInfo['prepayid']=$reponse['prepay_id'];
            $payInfo['package']='Sign=WXPay';
            $payInfo['noncestr']=$reponse['nonce_str'];
            $payInfo['timestamp']=time();//需要到毫秒
            $sign=$weixin->getSign($payInfo);
            $payInfo['sign']=$sign;
        }else{
            throw new ServerException('统一下单失败！');
        }
        return $payInfo;
    }

    /**
     * 微信jsapi支付
     * @param $orderSn
     * @param $price
     * @param $body
     * @param string $notify
     * @param $openid
     * @return array
     * @throws \app\common\model\ServerException
     */
    static public function weixinJsPay($orderSn,$price,$body,$notify='',$openid){
        $weixin=new WeixinPay();
        $price=round($price,2);
        $reponse=$weixin->getPrePayOrder2($body, $orderSn, $price,$notify,$openid);
        $payInfo=[];
        if($reponse['return_code']=='SUCCESS' && $reponse['result_code']=='SUCCESS')
        {
            $payInfo["appId"] = config('wechat.appid');
            $payInfo["timeStamp"] = (string)time();
            $payInfo["nonceStr"] = $weixin->createNoncestr();
            $payInfo["package"] = "prepay_id=".$reponse['prepay_id'];
            $payInfo["signType"] = "MD5";
            $payInfo["paySign"] = $weixin->getSign($payInfo);
        }else{
            throw new ServerException($reponse['return_msg']);
        }
        return $payInfo;
    }
    /**
     * 支付宝支付
     *
     * @param string $price 支付金额
     * @param array $orderSn 订单号
     * @param array $body 商品信息
     * @throws DeveloperException
     * @return string
     */
    static public function aliPay($orderSn,$price,$body,$notify='')
    {
        $zhifubao=new AliPay();
        $price=round($price,2);//保留两位，浮点
        $reponse=$zhifubao->aliResponse($body, $orderSn, $price,$notify);
        return $reponse;
    }
    /*微信退款*/
    static function wxRefund($order)
    {
        $merchid = config('weixinpay.mch_id');//商户号

        if(!$order){
            throw new ServerException('订单错误！');
        }

        $input = new \WxPayRefund();
        $input->SetOut_trade_no($order['order_sn']);         //自己的订单号

        $input->SetOut_refund_no($order['order_sn']);         //退款单号
        $input->SetTotal_fee($order['pay_money']*100);         //订单标价金额，单位为分
        $input->SetRefund_fee($order['pay_money']*100);            //退款总金额，订单总金额，单位为分，只能为整数
        $input->SetOp_user_id($merchid);
        $weixin=new \WxPayApi();
        $result = $weixin::refund($input); //退款操作
        return $result;
    }
    /*支付宝退款*/
    static function aliRefund($orderSn, $price)
    {
        $aop = new \AopClient ();
        $alipay = Config('alipay');//支付宝配置
        $aop->gatewayUrl = $alipay['gatewayUrl'];//请求的网关地址
        $aop->appId = $alipay['app_id'];//支付宝分配给开发者的应用ID
        $aop->rsaPrivateKey = $alipay['rsaPrivateKey'];//私钥
        $aop->alipayrsaPublicKey=$alipay['alipayrsaPublicKey'];//支付宝公钥
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayTradeRefundRequest();
        $request->setBizContent("{" .
            "\"out_trade_no\":\"$orderSn\"," .
            "\"refund_amount\":\"$price\"" .
            "  }");
        $result = $aop->execute($request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            $resultTrade_no = $result->$responseNode->trade_no;
            return array('resultCode'=>1,'resultTrade_no'=>$resultTrade_no);
        } else {
            $sub_msg = $result->$responseNode->sub_msg;
            return array('resultCode'=>0,'resultTrade_no'=>0,'error_msg'=>$sub_msg);
        }
    }
}